package com.etb.wisdom.eframe.rights.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.etb.core.utils.EncryptionUtil;
import com.etb.web.action.ETBAction;
import com.etb.web.eui.utils.EuiUtil;
import com.etb.web.utils.PartyUtil;
import com.etb.web.utils.WebUtil;
import com.etb.wisdom.eframe.auth.AuthConstant.AuthType;
import com.etb.wisdom.eframe.auth.AuthConstant.PartyType;
import com.etb.wisdom.eframe.model.EtbUser;
import com.etb.wisdom.eframe.rights.service.EtbUserService;

@Action("user")
@Namespace("/eframe/rights/etbuser")
public class EtbUserAction extends ETBAction<EtbUser> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2206908338202827065L;
	
	@Autowired
	public EtbUserService userService;	
	
	@Override
	public void save() {
		userService.save(dataObject);
	}

	public void getUnauthList() {
		String userid = request.getParameter("userid");
		Map<String, Object> hqlParams = new HashMap<String, Object>();
		hqlParams.put("partyid", userid);
		hqlParams.put("partytype", PartyType.user.toString());
		hqlParams.put("authtype", AuthType.role.toString());
		List list = service.queryByNamedsql("query.eframe.framework.auth.getUnauthList", hqlParams);
		EuiUtil.toGrid(list, null);
	}
	
	public void getAuthList() {
		String userid = request.getParameter("userid");
		Map<String, Object> hqlParams = new HashMap<String, Object>();
		hqlParams.put("partyid", userid);
		hqlParams.put("partytype", PartyType.user.toString());
		hqlParams.put("authtype", AuthType.role.toString());
		List list = service.queryByNamedsql("query.eframe.framework.auth.getAuthList", hqlParams);
		EuiUtil.toGrid(list, null);
	}
	
	public void saveRole() {
		String addRoleIds = request.getParameter("addRoleIds");
		String delRoleIds = request.getParameter("delRoleIds");
		String userId = request.getParameter("userid");
		userService.saveRole(userId, addRoleIds, delRoleIds);
	}
	
	public void resetPassword() throws InstantiationException, IllegalAccessException {
		userService.resetPassword(getSelectedData());
	}
	
	public void checkOldPassword() {
		String oldPassword = request.getParameter("value");
		EtbUser user = new EtbUser();
		user.setLoginname(party.getLoginName());
		service.extend(user);
		if(user.getPassword().equals(EncryptionUtil.encrypt(oldPassword))) {
			WebUtil.render(PASS);
		} else {
			WebUtil.render(UNPASS);
		}
	}
	
	public void saveNewPassword() {
		String oldPassword = request.getParameter("oldPassword");
		String newPassword = request.getParameter("newPassword");
		userService.saveNewPassword(PartyUtil.get().getLoginName(),oldPassword, newPassword);
	}
	
}